#include "server.hpp"

// void HandleEvent(EventLoop* loop, Channel*channel,int id) {
//      std::cout << "有了一个事件!!\n"; 
//     loop->timerRefresh(id);
// }

// void HandleClose(Channel *channel)
// {
//     DBG_LOG("close fd:%d", channel->Fd());
//     channel->remove(); // 移除监控
//     delete channel;
// }
// void HandleRead(Channel *channel)
// {
//     int fd = channel->Fd();
//     char buf[1024] = {0};
//     int ret = recv(fd, buf, 1023, 0);
//     if (ret <= 0)
//     {
//         return HandleClose(channel);
//     }
//     std::cout<<buf<<std::endl;
//     channel->enableWrite(); // 启动可写事件
// }

// void HandleWrite(Channel *channel)
// {
//     int fd = channel->Fd();
//     const char *data = "天气还不错!!";
//     int ret = send(fd, data, strlen(data), 0);
//     if (ret < 0)
//     {
//         return HandleClose(channel); // 关闭释放
//     }
//     channel->disableWrite(); // 关闭写监控
// }

// void HandleError(Channel *channel)
// {
//     return HandleClose(channel); // 关闭释放
// }

// void Acceptor1(int fd)
// {
//     conn_id
// }
// int main()
// {
//     EventLoop loop;
//     Acceptor acceptor(&loop,8500);
//     acceptor.setAcceptorCallback(std::bind(Acceptor1, std::placeholders::_1));
//     while(1){
//         loop.start();
//     }
//     lst_sock.shutDown();
//     return 0;
// }


class EchoServer {
    private:
        TcpServer _server;
        using ConnectionPtr = std::shared_ptr<Connection>;

    private:
        void OnConnected(const ConnectionPtr &conn) {
            DBG_LOG("NEW CONNECTION:%p", conn.get());
        }
        void OnClosed(const ConnectionPtr &conn) {
            DBG_LOG("CLOSE CONNECTION:%p", conn.get());
        }
        void OnMessage(const ConnectionPtr &conn, Buffer *buf) {
            conn->connectionSend(buf->readPos(), buf->readableSize());
            printf("OnMessage\n");
            // conn->shutdown();
        }
        void OnAny(const ConnectionPtr &conn){
            printf("OnAny\n");
        }
    public:
        EchoServer(int port):_server(port) {
            _server.setThreadCount(0);
            _server.enableInactiveRelease(10);
            _server.setClosedCallback(std::bind(&EchoServer::OnClosed, this, std::placeholders::_1));
            _server.setConnectedCallback(std::bind(&EchoServer::OnConnected, this, std::placeholders::_1));
            _server.setMessageCallback(std::bind(&EchoServer::OnMessage, this, std::placeholders::_1, std::placeholders::_2));
            _server.setAnyEventCallback(std::bind(&EchoServer::OnAny,this, std::placeholders::_1));
        }
        void Start() { _server.start(); }
};  

// void ClientEntry(){
//     Socket cli_sock;
//     cli_sock.createClient(8500, "127.0.0.1");
//     std::string str = "hello world!";
//     cli_sock.sockSend(str.c_str(), str.size());
// }


int main()
{
    EchoServer server(8500);
    // std::thread client(ClientEntry);
    // client.detach();
    server.Start();
    return 0;
}